package cc.decat.escript.codegen;

import cc.decat.escript.object.ESIntegerObject;
import cc.decat.escript.object.ESObject;
import cc.decat.escript.object.ESStringObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConstGenerate {
    private final List<ESObject> constObjectList;
    private final Map<Long, Integer> integerConstMap;
    private final Map<String, Integer> stringConstMap;
    private final Map<Double, Integer> floatConstMap;

    public ConstGenerate(List<ESObject> constObjectList) {
        this.constObjectList = constObjectList;
        this.integerConstMap = new HashMap<>();
        this.stringConstMap = new HashMap<>();
        this.floatConstMap = new HashMap<>();
    }

    public int addConstObject(ESObject obj) {
        int index = constObjectList.size();
        constObjectList.add(obj);
        return index;
    }

    public int getIntegerConstIndex(Long val) {
        if(integerConstMap.containsKey(val)) {
            return integerConstMap.get(val);
        }
        int index = addConstObject(ESIntegerObject.fromValue(val));
        integerConstMap.put(val, index);
        return index;
    }

    public int getStringConstIndex(String val) {
        if(stringConstMap.containsKey(val)) {
            return stringConstMap.get(val);
        }
        int index = addConstObject(ESStringObject.fromValue(val));
        stringConstMap.put(val, index);
        return index;
    }

    public int getFloatConstIndex(Double val) {
        if(floatConstMap.containsKey(val)) {
            return floatConstMap.get(val);
        }
        int index = addConstObject(null);
        floatConstMap.put(val, index);
        return index;
    }
}
